package com.dushibao.manage.article;

import com.alibaba.fastjson2.JSON;
import com.dushibao.entity.Article;
import com.dushibao.service.ArticleService;
import com.dushibao.service.impl.ArticleServiceImpl;
import com.dushibao.view.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/website/article/add")
public class AddServlet extends HttpServlet {
    ArticleService articleService = new ArticleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Map<String,Object> maps = new HashMap<>();

        //如果有id说明是编辑
        if(id !=null && id.length()>0){
            Article obj = articleService.getById(Long.parseLong(id));

            maps.put("editObj",obj);
        }

        ModelAndView mv = new ModelAndView("website/article/add",maps);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bw = req.getReader();
        String json = bw.readLine();

        Article article = JSON.parseObject(json, Article.class);

        Integer ret = articleService.saveOrUpdate(article);
        resp.getWriter().write(ret.toString());
    }
}
